<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.agentName"
        style="width: 200px;margin-right:15px;"
        class="filter-item"
        placeholder="请输入管理员姓名"
      ></el-input>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.agentPhone"
        style="width: 200px;margin-right:15px;"
        class="filter-item"
        placeholder="请输入管理员手机号"
      ></el-input>
      <el-select
        v-model="listQuery.agentType"
        clearable
        placeholder="请选择类型"
        style="width: 200px;margin-right:15px;"
        class="filter-item"
      >
        <el-option label="一级代理" value="1">一级代理</el-option>
        <el-option label="医院代理" value="2">医院代理</el-option>
        <el-option label="直营代理" value="3">直营代理</el-option>
      </el-select>
      <el-select
        v-model="listQuery.isFlag"
        clearable
        placeholder="请选择状态"
        style="width: 200px;margin-right:15px;"
        class="filter-item"
      >
        <el-option label="启用中" value="1">启用中</el-option>
        <el-option label="禁用中" value="2">禁用中</el-option>
      </el-select>

      <!-- <el-date-picker   
        style="margin-left:15px;vertical-align: top;"
        v-model="listQuery.date"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="timestamp"
        >
      </el-date-picker>-->
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 15px;"
        v-waves
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addclick()"
      >添加</el-button>
      <!-- <el-button  type='primary' class="filter-item" @click="handleDownload"  icon="el-icon-download"  :loading="downloadLoading">导出</el-button> -->
    </div>
    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="序号" prop="index" align="center" width="160px"/>
      <el-table-column label="管理员姓名" prop="agentName" align="center"/>
      <el-table-column label="管理员手机号" prop="agentPhone" align="center"/>
      <el-table-column label="管理员账号" prop="agentAccount" align="center"/>
      <el-table-column label="上级管理员账号" prop="oneAgentAccount" align="center"/>
      <el-table-column label="类型" prop="agentType" align="center" width="140px">
        <template slot-scope="scope">
          <div>{{scope.row.agentType == 1 ? '一级代理':scope.row.agentType == 2 ? '医院代理':'直营代理'}}</div>
        </template>
      </el-table-column>
      <el-table-column label="佣金比例" prop="agentCommissionRatio" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.agentCommissionRatio"
          >{{scope.row.agentCommissionRatio>0 ? scope.row.agentCommissionRatio+'%':'-' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="管理员状态" prop="isFlag" align="center">
        <template slot-scope="scope">
          <div>{{scope.row.isFlag == 2 ? '禁用中':'启用中'}}</div>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="ctime">
        <template slot-scope="scope">{{scope.row.cTime | parseTime}}</template>
      </el-table-column>
      <el-table-column
        label="操作"
        class-name="small-padding fixed-width"
        width="250px"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.isFlag == 2"
            @click="changeStatus(scope.row.agentId,1)"
          >启用</el-button>
          <el-button size="mini" type="danger" v-else @click="changeStatus(scope.row.agentId,2)">禁用</el-button>
          <el-button size="mini" type="primary" style="width:80px" @click="updateAgentPassword(scope.row.agentId)">重置密码</el-button>

          <el-button size="mini" type="primary" @click="editor(scope.row)">编辑</el-button>
          <router-link
            :to="{name:'administrator_detail', query: {agentId: scope.row.agentId,agentName: scope.row.agentName,agentPhone: scope.row.agentPhone,isFlag: scope.row.isFlag,cTime:scope.row.cTime }}"
          >
            <el-button v-if="scope.row.agentType==1" type="info">详情</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 添加弹框 -->
    <el-dialog title="新增管理员" :visible.sync="dialog.add">
      <el-form
        :model="bindQuery"
        :rules="bindRules"
        ref="bindForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="管理员姓名" prop="agentName">
          <el-input clearable v-model="bindQuery.agentName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="管理员手机号" prop="agentPhone">
          <el-input clearable v-model="bindQuery.agentPhone" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="agentType">
          <el-select
            v-model="bindQuery.agentType"
            clearable
            placeholder="请选择类型"
            style="width: 200px;margin-right:15px;"
            class="filter-item"
          >
            <el-option label="一级代理" value="1">一级代理</el-option>
            <el-option label="医院代理" value="2">医院代理</el-option>
            <el-option label="直营代理" value="3">直营代理</el-option>
          </el-select>
        </el-form-item>
        <div v-if="bindQuery.agentType==2">
          <el-form-item label="一级代理" prop="fid">
            <el-select
              clearable
              v-model="bindQuery.fid"
              @change="dropDownAgent"
              style="width: 100%"
              placeholder="请选择一级代理账号"
            >
              <el-option
                v-for="List in oneAngetList"
                :key="List.agentId"
                :label="List.agentAccount"
                :value="List.agentId"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="bindQuery.agentType==2||bindQuery.agentType==3">
          <el-form-item label="分成比例" prop="agentCommissionRatio">
            <el-input-number
              :precision="2"
              :step="0.01"
              :max="100"
              :min="0.01"
              clearable
              v-model="bindQuery.agentCommissionRatio"
              placeholder="请输入分成比例"
            ></el-input-number>
          </el-form-item>
        </div>

        <el-form-item label="账户" prop="agentAccount">
          <el-input clearable v-model="bindQuery.agentAccount" placeholder="请输入账户"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="agentPassword">
          <el-input type="password" clearable v-model="bindQuery.agentPassword" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="agentPassword2">
          <el-input
            type="password"
            clearable
            v-model="bindQuery.agentPassword2"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">添加</el-button>
      </div>
    </el-dialog>
    <!-- 编辑管理员 -->
    <el-dialog title="编辑管理员" :visible.sync="dialog1.add">
      <el-form
        :model="bindQuery1"
        :rules="bindRules"
        ref="bindForm1"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="管理员姓名" prop="agentName">
          <el-input clearable v-model="bindQuery1.agentName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="管理员手机号" prop="agentPhone">
          <el-input clearable v-model="bindQuery1.agentPhone" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <div v-if="bindQuery1.agentType==2||bindQuery1.agentType==3">
          <el-form-item label="分成比例" prop="agentCommissionRatio">
            <el-input-number
              :precision="2"
              :step="0.01"
              :max="100"
              :min="0.01"
              clearable
              v-model="bindQuery1.agentCommissionRatio"
              placeholder="请输入分成比例"
            ></el-input-number>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog1.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="adds">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  dropDownAgent,
  updateAgentIsFlag,
  addAgent,
  updateAgent,
  updateAgentPassword
} from "@/api/administrator";
import { validatePhone } from "@/utils/validate";
import pcq from "@/components/index";
import { parseTime } from "@/utils";
export default {
  name: "administrator_list",
  data() {
    var validatePassPhone = (rule, value, callback) => {
      if (!validatePhone(value)) {
        return callback(new Error("请填写正确的手机号码"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.bindQuery.agentPassword2 !== "") {
          this.$refs.bindForm.validateField("agentPassword2");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.bindQuery.agentPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      show: false,
      listQuery: {
        offset: 1,
        limit: 10,
        agentName: "",
        agentPhone: "",
        agentType: "",
        isFlag: "",
        date: ""
      },
      list: null,
      loading: {
        list: false,
        add: false
      },
      oneAngetList: null,
      dialog: {
        add: false
      },
      dialog1: {
        add: false
      },
      bindQuery: {
        agentName: "",
        agentPhone: "",
        agentAccount: "",
        agentType: "",
        fid: "",
        agentPassword: "",
        agentPassword2: "",
        agentCommissionRatio: ""
      },
      bindQuery1: {
        agentId: "",
        agentType: "",
        agentName: "",
        agentPhone: "",
        agentCommissionRatio: ""
      },
      bindRules: {
        agentPassword: [
          { validator: validatePass, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        agentPassword2: [
          {
            validator: validatePass2,
            message: "请再次输入密码",
            trigger: "blur"
          },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        agentName: [
          { required: true, message: "请输入运维人员姓名", trigger: "change" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ],
        agentPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePassPhone, trigger: "blur" }
        ],
        agentAccount: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        agentType: [{ required: true, message: "请选择类型", trigger: "blur" }]
      },
      downloadLoading: false
    };
  },
  components: {
    pcq
  },
  methods: {
    //导出

    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "管理员联系方式",
          "管理员姓名",
          "管理员类型",
          "管理员所属区域名称",
          "管理员管辖医院",
          "佣金比例"
        ];
        const filterVal = [
          "agentPhone",
          "agentName",
          "roleName",
          "address",
          "agentName",
          "commissionRatio"
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "管理员列表"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "cTime") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },

    //获列表
    async getLists() {
      this.loading.list = true;
      try {
        let { date, ...other } = this.listQuery;
        let [startTime, endTime] = date ? date : [];
        const { data } = await getList({ ...other, startTime, endTime });

        this.list = data.records.map((item, index) => ({
          index: index + 1,
          ...item
        }));

        this.total = data.total;
      } catch (error) {}
      this.loading.list = false;
    },

    //获取医院列表
    async dropDownAgent() {
      const { data } = await dropDownAgent();
      this.oneAngetList = data;
    },

    //禁用启用
    changeStatus(agentId, status) {
      let type = status == 1 ? "启用" : "禁用";
      this.$confirm(`是否${type}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data } = await updateAgentIsFlag({
            agentId: agentId,
            isFlag: status
          });
          this.$message({
            type: "success",
            message: `${type}成功!`
          });
          this.getLists();
        })
        .catch(() => {});
    },
 //禁用启用
    updateAgentPassword(agentId) {
      this.$confirm(`是否重置密码为123456?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data } = await updateAgentPassword({
            agentId: agentId,
          });
          this.$message({
            type: "success",
            message: `重置成功!`
          });
          this.getLists();
        })
        .catch(() => {});
    },

    //新增
    add() {
      this.$refs["bindForm"].validate(async valid => {
        if (valid) {
          this.loading.add = true;
          try {
            const { data } = await addAgent(this.bindQuery);
            this.$message({
              type: "success",
              message: `新增成功!`
            });
            this.dialog.add = false;
            this.loading.add = false;
            this.$refs["bindForm"].resetFields();
            this.getLists();
          } catch (error) {
            this.dialog.add = false;
            this.loading.add = false;
            this.$refs["bindForm"].resetFields();
          }
        }
      });
    },
    //编辑
    adds() {
      this.$refs["bindForm1"].validate(async valid => {
        if (valid) {
          this.loading.add = true;
          try {
            const { data } = await updateAgent(this.bindQuery1);
            this.$message({
              type: "success",
              message: `编辑成功!`
            });
            this.dialog1.add = false;
            this.getLists();
          } catch (error) {}
          this.loading.add = false;
        }
      });
    },
     addclick(){
  this.dialog.add=true
  this.dropDownAgent();
},
    //编辑渲染数据
    editor(item) {
      this.arr = [];
      this.dialog1.add = true;
      this.bindQuery1.agentId = item.agentId;
      this.bindQuery1.agentName = item.agentName;
      this.bindQuery1.agentType = item.agentType;
      this.bindQuery1.agentPhone = item.agentPhone;
      this.bindQuery1.agentCommissionRatio = item.agentCommissionRatio;
    },
    //查找
    handleFilter() {
      this.listQuery.offset = 1;
      this.getLists();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getLists();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.getLists();
    }
  },
  created() {
    this.getLists();
  }
};
</script>
